/**
 * 
 */
package com.explgo.backend.security;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.explgo.backend.domain.User;
import com.explgo.backend.jpa.UserRepository;


/**
 * Spring security user service.
 * 
 * @author Jialiang(Cain) wang
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private UserRepository userDao;
	
	@Autowired
	public UserDetailsServiceImpl(UserRepository userDao) {
		this.userDao = userDao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = userDao.findByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("Can't find user: " + username);
		}

		List<GrantedAuthority> auths = getAuthorities(user);
		user.setAuthorities(auths);
		
		return user;
	}

	private List<GrantedAuthority> getAuthorities(User user) {
		List<GrantedAuthority> auths = new LinkedList<GrantedAuthority>();

		GrantedAuthority userAuth = new GrantedAuthorityImpl("ROLE_USER");
		auths.add(userAuth);

		return auths;
	}
}
